<template>
  <div>
    <div class="headBar">
      <el-form ref="form" :model="form" :inline="true" label-width="80px">
        <el-form-item label='' width="50">
          <el-select v-model="form.parameter_id" filterable  placeholder="选择参数">
            <el-option
              v-for="item in ParamData"
              :key="item.key"
              :label="item.label"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间选择">
          <el-date-picker
            v-model="form.recorded_time"
            align="right"
            format="yyyy 年 MM 月 dd 日"
            placeholder="选择日期"
            type="date"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="高炉编号">-->
<!--          <el-select v-model="form.furnace_id" placeholder="请选择">-->
<!--            <el-option-->
<!--              v-for="item in furnace"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="">
          <el-input-number v-model="form.range[0]" :precision="2" :step="0.01" :min="0"
                           clearable placeholder="参数下界"></el-input-number>
        </el-form-item>
        <el-form-item label="">
          <el-input-number v-model="form.range[1]" :precision="2" :step="0.01" :min="0"
                           clearable placeholder="参数上界"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" type="success" @click="reset">重置</el-button>
        </el-form-item>

<!--          TODO:此部分功能多余不用呈现-->
<!--          <el-col :span="2">-->
<!--            <el-form-item>-->
<!--              <el-button icon="el-icon-upload2" type="primary" @click="upload">上传</el-button>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="2">-->
<!--            <el-form-item>-->
<!--              <el-button-->
<!--                v-loading.fullscreen.lock="isDerive"-->
<!--                element-loading-background="rgba(0, 0, 0, 0.8)"-->
<!--                element-loading-spinner="el-icon-loading"-->
<!--                element-loading-text="拼命导出中"-->
<!--                icon="el-icon-download" type="primary" @click="derive">导出</el-button>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
      </el-form>
    </div>
    <div class="tableData">
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
        border
        max-height="520px"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          label="高炉编号"
          prop="furnace_id"
          width="130">
        </el-table-column>
        <el-table-column
          column-key="date"
          label="数据时间"
          prop="recorded_time"
          sortable
          width="150"
        >
        </el-table-column>
<!--        <el-table-column-->
<!--          label="参数ID"-->
<!--          prop="parameter_id"-->
<!--          sortable-->
<!--          width="120">-->
<!--        </el-table-column>-->
        <el-table-column
          label="参数名称"
          prop="parameter_mean"
          width="180">
        </el-table-column>
        <el-table-column
          label="参数值"
          prop="value"
          width="150">
        </el-table-column>
        <el-table-column
          label="参数单位"
          prop="parameter_dimension"
          width="100"
        >
        </el-table-column>
        <el-table-column v-if="isManager" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20,30]"
        :total="totalRows"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="UploadDialog" title="上传数据">
      <el-row>
        <el-col :span="12">
          <el-button size="medium" style="margin-left: 5%" type="primary" @click="downloadModel">下载批量模板
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-upload
            :auto-upload="false"
            :before-upload="beforeUpload"
            :limit="1"
            :on-change="handleChange"
            accept=".xls,.xlsx"
            action='#'
            class="upload-demo"
          >
            <el-button slot="trigger" size="medium" type="primary">选择文件</el-button>
            <div v-if="isUploading">
              正在上传
              <i class="el-icon-loading"></i>
            </div>
            <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
          </el-upload>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog :visible.sync="EditDialog" title="编辑数据">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="参数值">
          <el-input v-model="editForm.value" clearable placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="EditDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "historicalData",
  data() {
    return {
      isDerive: false,
      isManager:false,
      UploadDialog: false,
      EditDialog: false,
      isUploading:false,
      loading: false,
      ParamData: [],
      tableData: [],
      editForm: {},
      form: {
        pageNow: 1,
        pageSize: 10,
        recorded_time: "",
        parameter_id: "",
        furnace_id: "BG4BF",
        range:[]
      },
      furnace: [
        {
          value: "BG4BF",
          label: "BG4BF"
        },
      ],
      pageNum: 1,
      pageSize: 10,
      totalRows: 1,
      fileList: [] // 保存正在上传的文件列表
    }
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 1) {
        return 'warning-row';
      }
    },
    // 下载批量模板
    downloadModel() {
      // 构建模板文件的URL
      const url = `${process.env.BASE_URL}dataModel.xlsx`;

      // 创建隐藏的a标签来触发下载
      const link = document.createElement('a');
      link.href = url;
      link.style.display = 'none';
      link.download = 'dataModel.xlsx'; // 设置下载文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 上传前的文件验证
    beforeUpload(file) {
      // 验证文件类型
      const isExcelOrCsv = file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'text/csv';
      if (!isExcelOrCsv) {
        this.$message.error('只能上传excel或csv文件！');
        return false; // 阻止上传
      }
      // 可以在这里添加其他验证逻辑，如大小限制等

      return true;
    },
    upload() {
      this.UploadDialog = true
      this.fileList = []
    },
    // 文件状态变化时处理，例如文件被添加或移除
    handleChange(file, fileList) {
      this.fileList = fileList
      if (file.status !== 'uploading') {
        this.uploadFile(file.raw); // 调用上传方法
      }
    },
    async uploadFile(file) {
      this.isUploading = true
      const formData = new FormData();
      formData.append('file', file); // 'file'是后端接收文件的参数名，需与后端约定
      try {
        const response = await this.$axios.post(this.$httpUrlHistoricalData + '/uploadFile', formData, { // 使用axios发送POST请求，替换为你的接口地址
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            // 进度条处理，可与handleProgress结合或单独处理
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            console.log(`Upload progress: ${percentCompleted}%`);
          }
        });
        if (response.data.code === 200) {
          this.$message.success('文件上传成功！');
          setTimeout(() => {
            console.log("异步加载，保证数据可查到")
          }, 500)
          this.loadHistoricalData()
        } else {
          this.$message.error(response.data.msg);
        }
        this.isUploading = false;
      } catch (error) {
        console.error('上传错误:', error);
        this.$message.error('文件上传出错！');
        this.isUploading = false;
      }
    },

    search() {
      this.pageNum = 1;
      if (this.form.range.length !== 0) {
        if (this.form.range[0] == null){
          this.form.range[0] = 0
        }
        if (this.form.range[1] == null){
          this.form.range[1] = 999999
        }
        if (this.form.range[0] > this.form.range[1]){
          this.$message.error("上界不能小于下界！")
          return
        }
      }
      this.loadHistoricalData()
    },
    reset() {
      this.form = {
        pageNow: 1,
        pageSize: 10,
        // 非字符串的内容，重置的时候一定要赋值为null
        recorded_time: null,
        parameter_id: "",
        furnace_id: "",
        range:[0, 999999]
      }
      this.loadHistoricalData()
    },
    async derive() {
      try {
        this.isDerive = true
        const response = await this.$axios.get(this.$httpUrlHistoricalData+'/downloadExcel', { responseType: 'blob' });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'example.xlsx'); // 设置下载的文件名
        document.body.appendChild(link);
        link.click();
        link.remove();
        this.isDerive = false
      } catch (error) {
        console.error('Error downloading file:', error);
      }
    },
    handleEdit(row){
      this.EditDialog = true
      this.editForm = row
    },
    confirmEdit(){
      this.$axios.post(this.$httpUrlHistoricalData + '/update', this.editForm).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.EditDialog = false
          this.loadHistoricalData()
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      }).catch(err =>{
        this.$message({
          message: "后台报错："+err,
          type: 'error'
        });
      })
    },

    handleDelete(row){
      this.$confirm('是否删除该条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post(this.$httpUrlHistoricalData + '/delete', row).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '操作成功！',
              type: 'success'
            });
            this.loadHistoricalData()
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(
          err => {
            this.$message({
              message: '操作失败！',
              type: 'error'
            });
          }
        )
      })

    },

    loadHistoricalData() {
      this.loading = true
      this.form.pageNow = this.pageNum
      this.form.pageSize = this.pageSize
      console.log(this.form)
      this.$axios.post(this.$httpUrlHistoricalData + "/getByPage", this.form).then(res => {
        res = res.data
        console.log(res)
        if (res.code === 200) {
          this.tableData = res.data.rowData
          this.totalRows = res.data.totalRows
        } else {
          this.$message.error({
            message: res.msg,
            type: 'error'
          })
        }
        this.loading = false
      }).catch(err => {
          this.$message({
            message: '加载数据失败！',
            type: 'error'
          });
          this.loading = false
        }
      )
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1
      this.pageSize = val
      this.loadHistoricalData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.loadHistoricalData()
    },
    getParameters(){
      this.$axios.get(this.$httpUrlVisualization+'/getParameters').then(res =>{
        res = res.data;
        console.log(res)
        if(res.code === 200){
          this.ParamData = []
          console.log("后端获取参数")
          console.log(res)
          this.parseParameter(res.data);
        }else{
          this.$message.error(res.msg);
        }
      })
    },
    parseParameter(param){
      for(let i=0;i<param.length;i++){
        this.ParamData.push({
          label: param[i].parameter_mean,
          key: param[i].parameter_id
        })
      }
      sessionStorage.setItem('ParamData', JSON.stringify(this.ParamData))
    },
  },
  mounted() {
    if(sessionStorage.getItem("UserStatue") === '2'){
      this.isManager = true
    }
    if (sessionStorage.getItem('ParamData')) {
      this.ParamData = JSON.parse(sessionStorage.getItem('ParamData'))
    } else {
      this.getParameters()
    }
    this.loadHistoricalData()
  }
}

</script>

<style scoped>
.headBar {
  padding: 12px 0px 0px 18px;
  border-radius: 0 0 15px 15px;
  box-shadow: 0 2px 8px 2px rgba(0, 0, 0, 0.1);
}

.tableData {
  display: flex;
  flex-direction: column;
  margin: 10px;
}
</style>
